package com.iqiyi.pps.epg.core.dao.record;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordPlan;
import com.iqiyi.pps.epg.api.model.web.record.TRecordPlanLibrary;
import com.iqiyi.pps.epg.api.model.web.record.TRecordPlanLibraryPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordPlanPage;
import com.iqiyi.pps.epg.core.dao.base.BaseDao;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.record.RecordPlan;
import com.iqiyi.pps.epg.core.utils.SqlUtil;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/11.
 */
@Component
public class RecordPlanDao extends BaseDao<RecordPlan> {
//    public static boolean isProductionEnv() {
//        return "production".equals(Configuration.getString("deploy.env"));
//    }

    public TRecordPlanPage findPlanPage(TPage page, TFilter filter) {
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        Page<RecordPlan> dbPage = TransUtil.buildPage(page);
        Page<RecordPlan> pageData = findPage(dbPage, filterList);
        List<RecordPlan> dataList = pageData.getResult();
        TRecordPlanPage dataPage = new TRecordPlanPage();
        page.setTotalCount(pageData.getTotalCount());
        dataPage.setTPage(page);
        List<TRecordPlan> tList = transToTRecordPlanList(dataList);
        dataPage.setResult(tList);
        return dataPage;
    }

    private List<TRecordPlan> transToTRecordPlanList(List<RecordPlan> dataList) {
        List<TRecordPlan> resultList = new ArrayList<>();
        TRecordPlan tPlan = null;
        for (RecordPlan tempData : dataList) {
            tPlan = transToTRecordPlan(tempData);
            resultList.add(tPlan);
        }
        return resultList;
    }

    public TRecordPlan transToTRecordPlan(RecordPlan tempData) {
        TRecordPlan _tEntity = new TRecordPlan();
        if (tempData == null) {
            return _tEntity;
        }
        _tEntity.setId(tempData.getId());
        _tEntity.setChannelId(tempData.getChannelId());
        _tEntity.setColId(tempData.getColId());
        _tEntity.setEnable(tempData.getEnable());
        _tEntity.setRepeatCode(tempData.getRepeatCode());
        _tEntity.setStatus(tempData.getStatus());
        _tEntity.setPlanType(tempData.getPlanType());
        _tEntity.setStartDate(tempData.getStartDate());
        _tEntity.setStopDate(tempData.getStopDate());
        _tEntity.setStartDayTime(tempData.getStartDayTime());
        _tEntity.setStopDayTime(tempData.getStopDayTime());
        _tEntity.setFragmentOutput(tempData.getFragmentOutput());
        _tEntity.setOpUser(tempData.getOpUser());
        _tEntity.setNotifyType(tempData.getNotifyType());
        _tEntity.setProjectWorkers(tempData.getProjectWorkers());
        return _tEntity;
    }

    public TRecordPlanLibraryPage findLibraryPage(TPage page, TFilter filter) {
        String tempPattern = "${PARAMS}";
        String resultPattern = " recordPlan.id,recordPlan.col_id,col.col_name,recordPlan.channel_id,channel.channel_name," +
                " col.category_id,col.has_auth,recordPlan.repeat_code,recordPlan.plan_type, " +
                " recordPlan.start_date,recordPlan.stop_date,recordPlan.start_day_time, recordPlan.stop_day_time,  " +
                " recordPlan.fragment_output,recordPlan.enable,recordPlan.op_user,recordPlan.create_time ";
        String totalPattern = "COUNT(*) as total";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String hql = "select " + tempPattern + " from record_plan recordPlan, record_channel channel,record_col col where recordPlan.channel_id = channel.id and recordPlan.col_id = col.id";
        String original = page.getOrderBy();
        page.setOrderBy(rebuildOrderBy(original, "recordPlan"));
        Page<TRecordPlanLibrary> dbPage = TransUtil.buildPage(page);
        String sql = SqlUtil.buildWithPropertyFilter(hql, filterList);
        boolean skipQuery = false;
        if (dbPage.isAutoCount()) {
            logger.debug("[build sql totalPattern]" + sql.replace(tempPattern, totalPattern));
            String totalCount = getSession().createSQLQuery(sql.replace(tempPattern, totalPattern))
                    .addScalar("total", new StringType()).list().get(0).toString();

            page.setTotalCount(Long.valueOf(totalCount));
            if (page.getTotalCount() == 0) {
                skipQuery = true;
                logger.debug("[skip query  case total is zero ]");
            }
        }
        List<TRecordPlanLibrary> dataList = new ArrayList<>();
        if (!skipQuery) {
            sql = SqlUtil.buildAppendPage(dbPage, sql);
            sql = SqlUtil.buildAppendPageLimit(dbPage, sql);
            logger.debug("[build sql resultPattern ]" + sql.replace(tempPattern, resultPattern));
            List result = getSession().createSQLQuery(sql.replace(tempPattern, resultPattern)).list();
            TRecordPlanLibrary singleData = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Object single : result) {
                Object[] obj = (Object[]) single;
                singleData = new TRecordPlanLibrary();
                singleData.setId(Long.valueOf("" + obj[0]));
                singleData.setColId(Long.valueOf("" + obj[1]));
                singleData.setColName("" + obj[2]);
                singleData.setChannelId(Long.valueOf("" + obj[3]));
                singleData.setChannelName("" + obj[4]);
                singleData.setCategoryId(Integer.valueOf("" + obj[5]));
                singleData.setHasAuth(Integer.valueOf("" + obj[6]));
                singleData.setRepeatCode(Integer.valueOf("" + obj[7]));
                singleData.setPlanType(Integer.valueOf("" + obj[8]));
                singleData.setStartDate("" + obj[9]);
                singleData.setStopDate("" + obj[10]);
                singleData.setStartDayTime("" + obj[11]);
                singleData.setStopDayTime("" + obj[12]);
                singleData.setFragmentOutput(Integer.valueOf("" + obj[13]));
                singleData.setEnable(Integer.valueOf("" + obj[14]));
                singleData.setOpUser("" + obj[15]);
                singleData.setCreateTime(sdf.format(obj[16]));
                dataList.add(singleData);
            }
        }
        TRecordPlanLibraryPage libraryPage = new TRecordPlanLibraryPage();
        page.setOrderBy(original);
        libraryPage.setTPage(page);
        libraryPage.setResult(dataList);
        return libraryPage;
    }

    private String rebuildOrderBy(String original, String aliasName) {
        String[] params = original.split(",");
        StringBuilder sBuilder = new StringBuilder();
        for (String param : params) {
            sBuilder.append(aliasName + "." + param);
            sBuilder.append(",");
        }
        if (sBuilder.length() > 0) {
            sBuilder.deleteCharAt(sBuilder.length() - 1);
        }
        return sBuilder.toString();
    }

    public void batchUpdate(List<RecordPlan> list){
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        try {
            for (RecordPlan temp : list) {
                session.update(temp);
            }
            transaction.commit();
        } catch (Exception e) {
            logger.error(e.getMessage());
            transaction.rollback();
        } finally {
            session.close();
        }
    }
}
